package com.yuchen.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuchen.learning.entity.User;
import com.yuchen.learning.mapper.UserMapper;
import com.yuchen.learning.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public boolean register(User user) {
        // 检查用户名唯一
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if (this.getOne(wrapper) != null) {
            return false;
        }
        // 简单加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        return this.save(user);
    }

    @Override
    public User login(String username, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = this.getOne(wrapper);
        if (user != null) {
            String inputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            if (inputPassword.equals(user.getPassword())) {
                return user;
            }
        }
        return null;
    }
}